<?php

namespace App\Console\Commands;


use App\Listeners\Listener;
use App\Model\Business\Schedule;
use App\Model\Business\ScheduleStuden;
use App\Model\Eeoapi\Eeocomment;
use App\Model\Eeoapi\Eeoschedule;
use App\Model\Eeoapi\Eeostudent;
use App\Model\Eeoapi\Eeosync;
use App\Model\Foundation\Student;
use App\Model\Foundation\Teacher;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;


class foo extends Command
{
    /**
     * sync every 15mins
     */

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:foo';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'sync attend info, videos replay and comments info  from class which have been finished 30 mins before';

    /**
     * Create a new command instance.
     *
     * @return void
     */


    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->getSchedule();
        $this->getVideoSchedule();
        $this->getCommentSchedule();
    }

    /**
     * 查询所有未同步且已经结束的课节
     * @param
     */
    protected function getSchedule()
    {
        $time = date('Y-m-d H:i:s',time()-60*30);
        $schedules = Schedule::where('eeosync', 0)
            ->where('endtime','<', $time)
            ->where('status', 1)
            ->get();
        foreach ($schedules as $schedule){
            $eeocourse = Eeoschedule::where('scheduleid',$schedule->scheduleid)
                ->first();
            $teacher = Teacher::where('teacheruid', $schedule->teacheruid)
                ->value('ClassInNo');
            $this->syncEeo($eeocourse->courseId,$eeocourse->classId,$teacher,$schedule->scheduleid);

        }
        echo "Sync Class Time Finished".' || ';
    }

    /**
     * 查询所有未同步且已经结束的课节
     * @param
     */
    protected function getVideoSchedule()
    {
        $time = date('Y-m-d H:i:s',time()-60*30);
        $schedules = Schedule::where('eeosyncvideo', 0)
            ->where('endtime','<', $time)
            ->where('status', 1)
            ->get();
        foreach ($schedules as $schedule){
            $eeocourse = Eeoschedule::where('scheduleid',$schedule->scheduleid)
                ->first();
            $this->synVideos($eeocourse->courseId,$eeocourse->classId,$schedule->scheduleid);

        }
        echo "Sync Class Videos Finished ||";
    }

    /**
     * 查询所有未同步评论数据且已经结束的课节
     * @param
     */
    protected function getCommentSchedule()
    {
        $time = date('Y-m-d H:i:s',time()-60*30);
        $schedules = Schedule::where('eeosynccomment', 0)
            ->where('endtime','<', $time)
            ->where('status', 1)
            ->get();
        if($schedules){
            foreach ($schedules as $schedule){
                $students = ScheduleStuden::where('scheduleid',$schedule->scheduleid)->get();
                if($students){
                    foreach ($students as $student){
                        $student = Student::find($student->studentuid);
                        if($student){
                            $eeostudent = Eeostudent::where('ClassInNo',$student->ClassInNo)->first();
                            $eeocourse = Eeoschedule::where('scheduleid',$schedule->scheduleid)->first();
                            try{
                                $data = $this->syncComments($eeostudent,$eeocourse);
                                if($data){
                                    foreach ($data as $item){
                                        if($item['class_id'] == $eeocourse->classId){
                                            $this->saveComments($item,$schedule->scheduleid,$student->studentuid);
                                        }
                                    }
                                }
                                $this->updateSyncComment($schedule->scheduleid);
                            }catch (\Exception $e){
                                continue;
                            }
                        }
                    }
                }
            }
        }

        echo "Sync Students Comments Finished";
    }


    /**
     * 同步课节学生评论信息
     * @param $eeostudent
     * @param $eeocourse
     * @return mixed
     * @throws \Exception
     */
    protected function syncComments($eeostudent,$eeocourse)
    {

        try{
            $listener = new Listener();
            if($eeostudent&&$eeocourse){
                $listener->setUri('getStudentCommentList');
                $data = $listener->dataMaker();
                $data["courseId"] = $eeocourse->courseId;
                $data["studentId"] = $eeostudent->studentId;
                $listener->setRequest($data);
                $result = $listener->callEeoApi();
                if($result['error_info']['errno'] == 1) {
                    return $result['data'];
                }
                else{
                    if($result['error_info']['errno'] == 106){
                        return null;
                    }else{
                        throw new \Exception($result['error_info']['error'], $result['error_info']['errno']);
                    }
                }
            }
        }catch (\Exception $e){
            throw $e;
        }
    }


    /**
     * 保存EEO 学生评论数据
     * @param $data
     * @param $scheduleid
     * @param $studentid
     *
     */
    protected function saveComments($data,$scheduleid,$studentid)
    {
        $fileds = [
            "scheduleid" => $scheduleid,
            "studentid" => $studentid,
            "star_level" => $data['star_level'],
            "comment" => $data['comment'],
            "class_status" => $data['class_status']
        ];
        Eeocomment::firstOrCreate($fileds);
    }

    protected function updateSyncComment($scheduleid)
    {

        try{
            Schedule::where('scheduleid',$scheduleid)
                ->update(['eeosynccomment' => 1]);
        }catch (\Exception $e){
            throw $e;
        }
    }

    /**
     * 同步课节用户时间到EEO
     * @param $courseId 课程id
     * @param $classId 课节id
     * @param $teacher 老师账号
     * @param $scheduleid
     */
    protected function syncEeo($courseId,$classId,$teacher,$scheduleid)
    {

        try{
            $listener = new Listener();
            if($courseId&&$classId){
                $listener->setUri('getClassMemberTime');
                $data = $listener->dataMaker();
                $data["courseId"] = $courseId;
                $data["classId"] = $classId;
                $listener->setRequest($data);
                $result = $listener->callEeoApi();
                if($result['error_info']['errno'] == 1) {
                    $this->saveData($scheduleid,2,$teacher,$result['data']['teacher']['FirstEnterTime'],
                        $result['data']['teacher']['LastExitTime'],$result['data']['teacher']['TeachTime']);
                    foreach ($result['data']['student'] as $student){
                        $this->saveData($scheduleid,1,$student['account'],$student['FirstEnterTime'],
                            $student['LastExitTime'],$student['StudyTime']);
                    }
                    $this->updateSync($scheduleid);
                }
                if($result['error_info']['errno'] == 106){
                    $this->updateSync($scheduleid);
                }
            }
        }catch (\Exception $e){
            throw $e;
        }
    }

    /**
     * 拉取课节视频地址
     * @param $courseId 课程id
     * @param $classId 课节id
     * @param $scheduleid
     */
    protected function synVideos($courseId,$classId,$scheduleid)
    {

        try{
            $listener = new Listener();
            if($courseId&&$classId){
                $listener->setUri('getClassVideo');
                $data = $listener->dataMaker();
                $data["courseId"] = $courseId;
                $data["classId"] = $classId;
                $listener->setRequest($data);
                $result = $listener->callEeoApi();
                $videosites = [];
                $code = $result['error_info']['errno'];
                if($code == 1) {
                    if($result['data']['VideoType'] == 'replay' && $result['data']['Code'] == 0){
                        if($result['data']['VodInfo']['FileList'])
                        foreach ($result['data']['VodInfo']['FileList'] as $items){
                            foreach ($items['Playset'] as $item ){
                                if(substr($item['Url'],-6,6) == 'f0.mp4'){
                                    $videosites[] = $item['Url'];
                                }
                            }
                        }
                    }
                    $this->saveVideo($scheduleid,$videosites);
                }
                if($code == 254){
                    $this->updateSyncVideos($scheduleid);
                }
//                else{
//                    throw new \Exception($result['error_info']['error'], $result['error_info']['errno']);
//                }
            }
        }catch (\Exception $e){
            throw $e;
        }
    }

    /**
     * 存储同步数据到数据库
     * @param $schedule
     * @param $type 学生为1 老师为2
     * @param $userid ClassInNo
     * @param $firstEnterTime 第一次进入教室时间
     * @param $lastExitTime 最后一次离开教室时间
     * @param $studyTime 有效学习时间
     */
    public function saveData($scheduleid,$type,$userid,$firstEnterTime,$lastExitTime,$studyTime)
    {
        try{
            $schedule = Schedule::find($scheduleid);
            $begintime = $schedule->begintime;
            $endtime = $schedule->endtime;
            $sync['scheduleid'] = $scheduleid;
            $sync['type'] = $type;
            $sync['userid'] = $userid;
            if($firstEnterTime){
                $sync['firstEnterTime'] = date('Y-m-d H:i:s',$firstEnterTime);
            }
            if($lastExitTime){
                $sync['lastExitTime'] = date('Y-m-d H:i:s',$lastExitTime);
            }
            $sync['studyTime'] = $studyTime;
            $sync['attend'] = 1;
            $sync['late'] = 0;
            $sync['Leave_early'] = 0;
            if($studyTime == 0){
                $sync['attend'] = 0;
            }else{
                if(!is_null($firstEnterTime) && $sync['firstEnterTime'] > $begintime){
                    $sync['late'] = 1;
                }
                if(!is_null($lastExitTime) && $sync['lastExitTime'] < $endtime){
                    $sync['Leave_early'] = 1;
                }
            }
            $eeosync = New Eeosync($sync);
            $eeosync->save();
        }catch (\Exception $e){
            throw $e;
        }
    }

    /**
     * 更改同步状态到数据库
     * @param $scheduleid
     */
    public function updateSync($scheduleid)
    {
        try{
            Schedule::where('scheduleid',$scheduleid)
                ->update(['eeosync' => 1]);
        }catch (\Exception $e){
            throw $e;
        }
    }


    /**
     * 更改同步状态到数据库
     * @param $scheduleid
     */
    public function updateSyncVideos($scheduleid)
    {
        try{
            Schedule::where('scheduleid',$scheduleid)
                ->update(['eeosyncvideo' => 1]);
        }catch (\Exception $e){
            throw $e;
        }
    }

    /**
     * 存储同步视频地址
     *
     */
    public function saveVideo($scheduleid,$videosites)
    {
        try{
            if($videosites)
                foreach ($videosites as $videosite){
                    DB::table('schedules_videos')
                        ->insert(
                           ['scheduleid' => $scheduleid, 'videosite' => $videosite]
                        );
            }else
                DB::table('schedules_videos')
                    ->insert(
                        ['scheduleid' => $scheduleid, 'videosite' => "No Videos recorded" ]
                    );
            $this->updateSyncVideos($scheduleid);
        }catch (\Exception $e){
            throw $e;
        }
    }

}
